// @ts-ignore
import path from 'path'
import type {ConfigEnv, PluginOption, UserConfig} from 'vite'
import {loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import {VitePWA} from 'vite-plugin-pwa'
// 自动导入composition api 和 生成全局typescript说明
import AutoImport from 'unplugin-auto-import/vite'
import {NaiveUiResolver} from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import Icons from 'unplugin-icons/vite'
// @ts-ignore
import vueJsx from '@vitejs/plugin-vue-jsx';
// @ts-ignore
import topLevelAwait from 'vite-plugin-top-level-await'
// @ts-ignore
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
const pathSrc = path.resolve(__dirname, 'src')

// @ts-ignore
function setupPlugins(env: ImportMetaEnv): PluginOption[] {
	return [
		vue(),
		vueJsx({}),
		VueSetupExtend(),
		topLevelAwait({
			promiseExportName: '__tla',
			promiseImportName: (i: any) => `__tla_${i}`
		}),

		{
			postcssPlugin: 'internal:charset-removal',
			AtRule: {
				charset: (atRule: any) => {
					if (atRule.name === 'charset') {
						atRule.remove()
					}
				}
			}
		},
		env.VITE_GLOB_APP_PWA === 'true' && VitePWA({
			injectRegister: 'auto',
			manifest: {
				name: 'chatGPT',
				short_name: 'chatGPT',
				icons: [
					{
						src: 'pwa-192x192.png',
						sizes: '192x192',
						type: 'image/png'
					},
					{
						src: 'pwa-512x512.png',
						sizes: '512x512',
						type: 'image/png'
					},
				],
			},
		}),
		AutoImport({
			imports: [
				'vue',
				'vue-router',
				'pinia',
				{axios: [['default', 'axios']]}
			],
			dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
			eslintrc: {
				enabled: true,
				filepath: './.eslintrc-auto-import.json',
				globalsPropValue: true,
			},
		}),
		Components({
			dts: path.resolve(pathSrc, 'components.d.ts'),
			// 按需加载的文件夹
			dirs: ['src/components'],
			// 按需加载
			resolvers: [
				NaiveUiResolver(),
			],
		}),
		Icons({
			autoInstall: true,
		}),

	]
}

export default ({mode}: ConfigEnv): UserConfig => {
	// @ts-ignore
	const viteEnv = loadEnv(mode, process.cwd()) as unknown as ImportMetaEnv
	return {
		base: viteEnv.VITE_PUBLIC_PATH,
		resolve: {
			alias: {
				'@': path.resolve(process.cwd(), 'src'),
			},
		},
		plugins: setupPlugins(viteEnv),
		server: {
			host: '127.0.0.1',
			port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),
			strictPort: true,
			open: true,
			proxy: {
				[`${viteEnv.VITE_APP_BASE_API}`]: {
					target: viteEnv.VITE_APP_API_BASE_URL,
					changeOrigin: true,
					rewrite: path => path.replace(new RegExp(`^${viteEnv.VITE_APP_BASE_API}`), '')
				},
			},
		},
		build: {
			// 分块打包，分解块，将大块分解成更小的块
			chunkSizeWarningLimit: 3000,
			rollupOptions: {
				output: {
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id
								.toString()
								.split('node_modules/')[1]
								.split('/')[0]
								.toString();
						}
					},
					chunkFileNames: (chunkInfo) => {
						const facadeModuleId = chunkInfo.facadeModuleId
							? chunkInfo.facadeModuleId.split('/')
							: [];
						const fileName =
							facadeModuleId[facadeModuleId.length - 2] || '[name]';
						return `js/${fileName}/[name].[hash].js`;
					}
				}
			},
			target: 'modules',
			outDir: 'docker/dist',           // 指定输出路径
			assetsDir: 'static',      // 指定生成静态资源的存放路径
			minify: 'terser',         // 混淆器,terser构建后文件体积更小
			sourcemap: false,         // 输出.map文件
			terserOptions: {
				compress: {
					drop_console: true,   // 生产环境移除console
					drop_debugger: true   // 生产环境移除debugger
				}
			},
			reportCompressedSize: false,
			commonjsOptions: {
				ignoreTryCatch: false,
			},
		},
	}
}
